package com.smart.vista.dialog;

import com.smart.comp.jcombobox.ObjetoCombo;
import com.smart.comp.jcombobox.ResultSetComboBoxModel;
import com.smart.comp.jcombobox.ResultSetComboBoxModelObject;
import com.smart.entity.Articulos;
import com.smart.entity.Grupos;
import com.smart.main.Transaccion;
import com.smart.vista.panel.ArticulosVista;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.swing.JOptionPane;

public class ArticulosNuevo extends javax.swing.JDialog {

    private Articulos objArticuloParaActualizar = null;
    private ResultSetComboBoxModel modeloCboBoxModel = null;

    public ArticulosNuevo(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        getGrupo();
        txtCosto.setText("0.0");
        txtCodigoArticulo.grabFocus();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        panel2 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        txtCodigoArticulo = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtCosto = new com.smart.comp.TextoMoneda();
        txtDescripcion = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        cboGrupo = new javax.swing.JComboBox();
        pnlBotones = new javax.swing.JPanel();
        btnGuardar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Nuevo Articulo");
        setResizable(false);

        panel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        panel2.setLayout(new java.awt.GridBagLayout());

        jLabel4.setText("Codigo:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        panel2.add(jLabel4, gridBagConstraints);

        txtCodigoArticulo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodigoArticuloKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 0.5;
        panel2.add(txtCodigoArticulo, gridBagConstraints);

        jLabel5.setText("Costo:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        panel2.add(jLabel5, gridBagConstraints);

        jLabel6.setText("Descripcion:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        panel2.add(jLabel6, gridBagConstraints);

        txtCosto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCostoKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 0.5;
        panel2.add(txtCosto, gridBagConstraints);

        txtDescripcion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtDescripcionKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 5;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        panel2.add(txtDescripcion, gridBagConstraints);

        jLabel1.setText("              ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 0.5;
        panel2.add(jLabel1, gridBagConstraints);

        jLabel2.setText("              ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 0.5;
        panel2.add(jLabel2, gridBagConstraints);

        jLabel3.setText("              ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        panel2.add(jLabel3, gridBagConstraints);

        jLabel7.setText("              ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        panel2.add(jLabel7, gridBagConstraints);

        jLabel8.setText("             ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        panel2.add(jLabel8, gridBagConstraints);

        jLabel9.setText("Grupo.");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        panel2.add(jLabel9, gridBagConstraints);

        cboGrupo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cboGrupoKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        panel2.add(cboGrupo, gridBagConstraints);

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/smart/recursos/disckete.png"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/smart/recursos/salir.png"))); // NOI18N
        btnSalir.setText("Salir");
        btnSalir.setToolTipText("Salir");
        btnSalir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSalir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlBotonesLayout = new javax.swing.GroupLayout(pnlBotones);
        pnlBotones.setLayout(pnlBotonesLayout);
        pnlBotonesLayout.setHorizontalGroup(
            pnlBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlBotonesLayout.createSequentialGroup()
                .addContainerGap(405, Short.MAX_VALUE)
                .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        pnlBotonesLayout.setVerticalGroup(
            pnlBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBotonesLayout.createSequentialGroup()
                .addGroup(pnlBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSalir)
                    .addComponent(btnGuardar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlBotones, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(panel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 613, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addComponent(pnlBotones, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        this.setVisible(false);
}//GEN-LAST:event_btnSalirActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        int rpta1 = JOptionPane.showConfirmDialog(this, "Seguro de Guardar el Articulo", this.getTitle(), JOptionPane.YES_NO_OPTION);
        if (rpta1 == JOptionPane.YES_OPTION) {
            if (validaCampos()) {
                String codigoArticulo = txtCodigoArticulo.getText();
                String descripcion = txtDescripcion.getText();
                Double costo = Double.parseDouble(txtCosto.getText());
                Locale.setDefault(Locale.ENGLISH);
                DecimalFormat costoFormato = new DecimalFormat("0.00");
                Integer codigoGrupo = ((ResultSetComboBoxModelObject) cboGrupo.getSelectedItem()).getCodigo();
                String HQLGrupos = "from Grupos g where g.idgrupo=" + codigoGrupo;
                List<Grupos> lstGrupos = Transaccion.executeHQLQuery(HQLGrupos);
                if (objArticuloParaActualizar == null) { //Nuevo Articulo
                    Articulos objArticuloNuevo = new Articulos();
                    objArticuloNuevo.setCodigoarticulo(codigoArticulo);
                    objArticuloNuevo.setDescripcion(descripcion);
                    objArticuloNuevo.setCosto(costo);
                    objArticuloNuevo.setGrupos(lstGrupos.get(0));
                    Transaccion.getSession().save(objArticuloNuevo);
                    Articulos idArticulos = (Articulos) Transaccion.getSession().get(objArticuloNuevo.getClass(), objArticuloNuevo.getIdarticulo());
                    int id = idArticulos.getIdarticulo();
                    Transaccion.closeSession();
                    Object object[] = {id, codigoArticulo, descripcion, costoFormato.format(costo), lstGrupos.get(0).getDescripcion(), "0"};
                    ArticulosVista.getModeloTblArticulos().addRow(object);
                } else { //Actualizar Articulo
                    if (validaCamposActualizar(objArticuloParaActualizar.getCodigoarticulo())) {
                        objArticuloParaActualizar.setCodigoarticulo(codigoArticulo);
                        objArticuloParaActualizar.setDescripcion(descripcion);
                        objArticuloParaActualizar.setCosto(costo);
                        objArticuloParaActualizar.setGrupos(lstGrupos.get(0));
                        Transaccion.getSession().update(objArticuloParaActualizar);
                        Transaccion.closeSession();
                        objArticuloParaActualizar = null;
                    } else {
                        return;
                    }
                }
                int rpta2 = JOptionPane.showConfirmDialog(this, "Desea registrar otro Articulo?", this.getTitle(), JOptionPane.YES_NO_OPTION);
                if (rpta2 == JOptionPane.YES_OPTION) {
                    limpiar();
                } else {
                    this.setVisible(false);
                }
            }
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void txtCodigoArticuloKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoArticuloKeyPressed
        if (evt.getKeyChar() == KeyEvent.VK_ENTER) {
            txtCodigoArticulo.transferFocus();
        }
    }//GEN-LAST:event_txtCodigoArticuloKeyPressed

    private void txtDescripcionKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescripcionKeyPressed
        if (evt.getKeyChar() == KeyEvent.VK_ENTER) {
            txtDescripcion.transferFocus();
        }
    }//GEN-LAST:event_txtDescripcionKeyPressed

    private void txtCostoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCostoKeyPressed
        if (evt.getKeyChar() == KeyEvent.VK_ENTER) {
            txtCosto.transferFocus();
        }
    }//GEN-LAST:event_txtCostoKeyPressed

    private void cboGrupoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cboGrupoKeyPressed
        if (evt.getKeyChar() == KeyEvent.VK_ENTER) {
            cboGrupo.transferFocus();
        }
    }//GEN-LAST:event_cboGrupoKeyPressed

    private void limpiar() {
        txtCodigoArticulo.setText("");
        txtDescripcion.setText("");
        txtCosto.setText("");
        cboGrupo.setSelectedIndex(-1);
        txtCodigoArticulo.grabFocus();
    }

    private boolean validaCampos() {
        boolean validado = true;
        String HQL = "from Articulos a where a.codigoarticulo='" + txtCodigoArticulo.getText() + "'";
        List<Articulos> lstArticuloBuscado = Transaccion.executeHQLQuery(HQL);
        String codArticulo = "";
        for (Articulos articulos : lstArticuloBuscado) {
            codArticulo = articulos.getCodigoarticulo();
        }
        if (txtCodigoArticulo.getText().equals("")) {
            validado = false;
            JOptionPane.showMessageDialog(this, "Ingrese el Codigo del Articulo");
            txtCodigoArticulo.grabFocus();
        } else if (!codArticulo.equals("") && objArticuloParaActualizar == null) {
            validado = false;
            JOptionPane.showMessageDialog(this, "El codigo del articulo: " + txtCodigoArticulo.getText() + " existe");
            txtCodigoArticulo.setText("");
            txtCodigoArticulo.grabFocus();
        } else if (txtDescripcion.getText().equals("")) {
            validado = false;
            JOptionPane.showMessageDialog(this, "Ingrese la Descripcion");
            txtDescripcion.grabFocus();
        } else if (txtCosto.getText().equals("")) {
            validado = false;
            JOptionPane.showMessageDialog(this, "Ingrese el Costo");
            txtCosto.grabFocus();
        } else if (modeloCboBoxModel.getSelectedDescri().equals("")) {
            validado = false;
            JOptionPane.showMessageDialog(this, "Elija un Grupo");
            cboGrupo.grabFocus();
        }
        return validado;
    }

    private boolean validaCamposActualizar(String codigo) {
        boolean validado = true;
        String HQL = "from Articulos a where a.codigoarticulo=" + codigo;
        List<Articulos> objArticuloBuscado = Transaccion.executeHQLQuery(HQL);
        if (objArticuloBuscado != null) {
            if (!objArticuloBuscado.get(0).getCodigoarticulo().equals(codigo)) {
                validado = false;
                JOptionPane.showMessageDialog(this, "El codigo del articulo: " + txtCodigoArticulo.getText() + " existe");
                txtCodigoArticulo.setText("");
                txtCodigoArticulo.grabFocus();
            }
        }
        return validado;
    }

    private void getGrupo() {
        try {
            String HQL = "from Grupos";
            List<Grupos> lstGrupos = Transaccion.executeHQLQuery(HQL);
            ObjetoCombo objectoCombo;
            ArrayList<ObjetoCombo> lstObjetoCombo = new ArrayList();
            for (Grupos objGrupos : lstGrupos) {
                objectoCombo = new ObjetoCombo();
                objectoCombo.setCodigo(objGrupos.getIdgrupo());
                objectoCombo.setDescri(objGrupos.getDescripcion());
                lstObjetoCombo.add(objectoCombo);
            }
            modeloCboBoxModel = new ResultSetComboBoxModel(lstObjetoCombo);
            cboGrupo.setModel(modeloCboBoxModel);
            cboGrupo.setSelectedIndex(-1);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public void setObjArticuloParaActualizar(Articulos objArticuloParaActualizar) {
        this.objArticuloParaActualizar = objArticuloParaActualizar;
        if (objArticuloParaActualizar != null) {
            txtCodigoArticulo.setText(objArticuloParaActualizar.getCodigoarticulo());
            txtDescripcion.setText(objArticuloParaActualizar.getDescripcion());
            txtCosto.setText(String.valueOf(objArticuloParaActualizar.getCosto()));
            ResultSetComboBoxModelObject rscbm = new ResultSetComboBoxModelObject(objArticuloParaActualizar.getGrupos().getIdgrupo(), objArticuloParaActualizar.getGrupos().getDescripcion());
            modeloCboBoxModel.setSelectedItem(rscbm);
            txtDescripcion.grabFocus();
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JComboBox cboGrupo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel panel2;
    private javax.swing.JPanel pnlBotones;
    private javax.swing.JTextField txtCodigoArticulo;
    private javax.swing.JTextField txtCosto;
    private javax.swing.JTextField txtDescripcion;
    // End of variables declaration//GEN-END:variables
}
